<template>
  <div class="pages personDetail">
    <div class="pageLevel">
      <div class="form-content">
        <!-- 操作框 -->
        <div class="operationBox tableSearch">
          <el-button type="primary" @click="goBack" size="mini" v-if="checkAdvInfo">返回</el-button>
          <el-button type="primary" @click="closeAdd" size="mini" v-else>返回</el-button>
        </div>
        <!-- 表单内容 -->
        <el-form
          :label-position="ruleForm.labelPosition"
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
          class="demo-ruleForm"
          size="small"
        >
          <div>
            <div class="rowtwo">
              <el-row class="rowtwo-form">
                <el-form-item label="广告标题" prop="title">
                  <el-input
                    show-word-limit
                    type="text"
                    v-model="ruleForm.title"
                    maxlength="16"
                    :disabled="checkAdvInfo"
                  ></el-input>
                </el-form-item>

                <el-form-item label="广告位置" prop="position">
                  <el-select
                    :disabled="checkAdvInfo "
                    v-model="ruleForm.position"
                    placeholder="请选择"
                    style="width: 100%;"
                  >
                    <el-option
                      v-for="item in positionArray"
                      :key="item.typeId"
                      :value="item.typeId"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-row>
              <el-row class="rowtwo-img">
                <el-form-item prop="imgUrl" label="广告图片">
                  <div
                    class="uploadTip"
                  >上传图片的最佳尺寸像素: 702*300像素，其他尺寸会影响页面效果，格式png，jpeg，jpg，gif</div>
                  <div :class="['imgbox',{'imgbox-v':!ruleForm.imgUrL}]">
                    <img :src="ruleForm.imgUrl" @click="showimg(ruleForm.imgUrl)" alt>
                  </div>
                  <el-upload
                    v-if="!ting"
                    class="upload-demo"
                    action="1"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :http-request="uploadSectionFile2"
                  >
                    <el-button
                      :disabled="checkAdvInfo"
                      class="upload-btn"
                      size="small"
                      type="primary"
                    >上传图片</el-button>
                  </el-upload>
                  <el-button
                    size="small"
                    class="delete-img"
                    @click="deleteImg"
                    :disabled="deletShow"
                  >删除</el-button>
                </el-form-item>
              </el-row>
            </div>
            <el-row style="width: 600px">
              <el-form-item label="广告有效期" prop="validityStartTime">
                <el-date-picker
                  v-model="ruleForm.validityStartTime"
                  :disabled="startTimeDisabled || checkAdvInfo"
                  type="datetime"
                  :clearable="clearable"
                  placeholder="选择开始时间"
                  @change="checkEndTime"
                  :picker-options="pickerOptions"
                ></el-date-picker>
                <el-checkbox
                  v-model="ruleForm.onLineLimit"
                  @change="startTimeLimit"
                  :disabled="checkAdvInfo"
                >不限制(即时上架)</el-checkbox>
              </el-form-item>
              <el-form-item prop="validityEndTime">
                <el-date-picker
                  v-model="ruleForm.validityEndTime"
                  :disabled="endTimeDisabled || checkAdvInfo"
                  type="datetime"
                  :clearable="clearable"
                  placeholder="选择结束时间"
                  :picker-options="pickerOptions"
                  @change="checkEndTime"
                ></el-date-picker>
                <el-checkbox
                  v-model="ruleForm.offlineLimit"
                  @change="endTimeLimit"
                  :disabled="checkAdvInfo"
                >不限制(即时下架 )</el-checkbox>
              </el-form-item>
            </el-row>
            <el-row style="width: 600px">
              <el-form-item label="广告链接" prop="link">
                <el-button
                  size="small"
                  type="primary"
                  @click="addLink"
                  :disabled="checkAdvInfo"
                >添加链接</el-button>
                <el-input placeholder="选填, 带入所选链接" class="link-input" v-model="ruleForm.linkUrl" disabled></el-input>
              </el-form-item>
            </el-row>
            <el-row style="width: 600px" v-if="!checkAdvInfo">
              <el-button size="small" @click="closeAdd">关闭</el-button>
              <el-button size="small" type="primary" @click="release">发布</el-button>
            </el-row>
          </div>
        </el-form>
      </div>
      <!-- 添加链接 -->
      <el-dialog
        title="添加链接"
        class="add-link"
        :visible.sync="dialogTableVisible_o"
        width="60%"
        height="500px"
      >
        <el-tabs type="border-card">
          <el-tab-pane label="网址链接">
            <label for>跳转链接</label>
            <el-input v-model="ruleForm.linkUrl" class="link-input" size="small" type="url"></el-input>
            <div class="btnBox">
              <el-button type="primary" size="small" @click="addLinkUrl">确定</el-button>
              <el-button size="small" @click="dialogTableVisible_o = false">取消</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="在线课程">
            <el-input v-model="searchClassInput" class="link-input" size="small"></el-input>
            <el-button size="small" @click="searchClass">搜索</el-button>
            <template>
              <div>
                <el-table :data="onlineClassList" stripe style="width: 100%" height="310">
                  <el-table-column width="40">
                    <template slot-scope="scope">
                      <el-radio
                        class="radio"
                        v-model="radio"
                        :label="scope.$index"
                        @change.native="readioChange(scope.row)"
                      ></el-radio>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="releaseTime"
                    label="创建时间"
                    width="180"
                    :formatter="forCreatedTime"
                  ></el-table-column>
                  <el-table-column prop="dataType" label="分类" width="80" :formatter="classify"></el-table-column>
                  <el-table-column prop="title" label="标题" width="200"></el-table-column>
                  <el-table-column prop="courseType" label="类型" width="80" :formatter="courseType"></el-table-column>
                  <el-table-column prop="sImgUrl" label="封面" width="170">
                    <template slot-scope="scope">
                      <img :src="scope.row.sImgUrl" class="head_pic">
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态" :formatter="classStatus"></el-table-column>
                </el-table>
                <div class="pageblock">
                  <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="['5','10','15',20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalItems"
                  ></el-pagination>
                  <el-button size="small" type="primary" class="topage" @click="toPage">确定</el-button>
                </div>
              </div>
            </template>
            <div class="btnBox">
              <el-button type="primary" size="small" @click="addOnlingCladdUrl">确定</el-button>
              <el-button size="small" @click="dialogTableVisible_o = false">取消</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import util from "@/util";
import s from "@/util/state";
import u from "@/util";
import {
  uploadFile,
  getFile,
  newAdv,
  queryCourse,
  updAdv,
  advInfo
} from "@/api";
export default {
  computed: mapState(["merchantId", "path", "power"]),
  components: {},

  data() {
    var checkstartTime = (rule, value, callback) => {
      callback();
    };
    var checkEndTime = (rule, value, callback) => {
      callback();
    };
    return {
      clearable: false,
      ting: false,
      id: "",
      status: "",
      dialogTableVisible_o: false,
      ruleForm: {
        title: "",
        position: 0,
        imgUrl: "",
        linkUrl: "",
        linkType: "",
        validityStartTime: "",
        validityEndTime: "",
        onLineLimit: false,
        offlineLimit: false
      },
      startTimeDisabled: false,
      endTimeDisabled: false,
      positionArray: [
        {
          typeId: 0,
          name: "首页轮播图"
        },
        {
          typeId: 1,
          name: "课堂页轮播图"
        }
      ],
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { min: 1, max: 16, message: "长度在 1 到 16 个字符", trigger: "blur" }
        ],
        position: [
          {
            required: true,
            message: "请至少选择一个分类",
            trigger: "change"
          }
        ],
        imgUrl: [{ required: true, message: "请上传图片", trigger: "blur" }],
        validityStartTime: [
          {
            // type:'datetime',
            required: true,
            message: "请选择开始日期",
            trigger: "blur"
          },
          {
            tigger: "change",
            validator: checkstartTime
          }
        ],
        validityEndTime: [
          {
            // type:'datetime',
            required: true,
            message: "请选择结束日期",
            trigger: "blur"
          },
          {
            tigger: "change",
            validator: checkEndTime
          }
        ]
      },
      inputLink: "",
      radio: "",
      onlineClassList: [],
      selectClass: {},
      searchClassInput: "",
      checkAdvInfo: false,
      currentPage: 1,
      pageSize: 20,
      totalItems: 0,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      },
      showUrl: "",
      deletShow: true
    };
  },
  created() {
    this.id = u.getQuery("id");
    this.status = u.getQuery("status");
    if (this.id != "") {
      if (this.status == 1) {
        this.checkAdvInfo = true;
        this.deletShow = true;
      }
      advInfo(this.id).then(res => {
        this.ruleForm = res.data;
        if (this.status == 2) {
          this.ruleForm.validityStartTime = "";
          this.ruleForm.validityEndTime = "";
        }
      });
    }
  },
  methods: {
    courseType: s.courseType,
    classify: s.courseClassify,
    classStatus: s.classStatus,
    forStartTime(row) {
      let year = u.foryear(parseInt(row.validityStartTime));
      let time = u.fortime(parseInt(row.validityStartTime));
      return year + " " + time;
    },

    forCreatedTime(row) {
      let year = u.foryear(parseInt(row.createTime));
      let time = u.fortime(parseInt(row.createTime));
      return year + " " + time;
    },
    goBack() {
      history.back();
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let postdata = {
            companyId: this.merchantId,
            title: this.ruleForm.title,
            position: this.ruleForm.position,
            imgUrl: this.ruleForm.imgUrl,
            validityStartTime: this.ruleForm.validityStartTime,
            validityEndTime: this.ruleForm.validityEndTime,
            linkType: this.ruleForm.linkType,
            linkUrl: this.ruleForm.linkUrl,
            appId: 0
          };

          if (this.id != "") {
            postdata.id = this.id;
            updAdv(postdata).then(res => {
              if (res.code == 200) {
                this.$message({
                  showClose: true,
                  message: "编辑成功",
                  type: "success"
                });

                history.back(-1);
                return false;
              } 
            })
          } else {
            newAdv(postdata).then(res => {
              if (res.code == 200) {
                this.$message({
                  showClose: true,
                  message: "新建成功",
                  type: "success"
                });

                history.back(-1);
                return false;
              } 
            });
          }
        } else {
          this.$message({
            showClose: true,
            message: "请检查必填信息",
            type: "error"
          });
          return false;
        }
      });
    },

    // 上传图片之前验证图片格式
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg" ||
        file.type === "image/gif";
      // const isLt2M = file.size / 1024 < 40;
      if (!isJPG) {
        this.$message.error("上传图片格式错误!");
      }
      // if (!isLt2M) {
      //   this.$message.error("上传图片大小不能超过 40kb!");
      // }
      const isSize = new Promise(function (resolve, reject) {
          let width = 702;
          let height = 300;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function () {
            let valid = img.width == width && img.height == height;
            valid ? resolve() : reject();
          }
          img.src = _URL.createObjectURL(file);
        }).then(() => {

        }, () => {
          this.$message.error('上传的图片必须是702px x 300px')
          return Promise.reject();
        });
        
      return isJPG && isSize;
    },
    //上传图片
    uploadSectionFile2(param) {
      var fileObj = param.file;
      var data = new FormData();
      data.append("file", fileObj);
      data.append("projectName", fileObj.name);
      uploadFile(data).then(res => {
        this.ruleForm.imgUrl = `${getFile}?id=${res.data.id}`;
        this.deletShow = false;
      });
    },

    deleteImg() {
      this.$confirm("您确认要删除当前图片么?", "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          this.ruleForm.imgUrl = "";
          this.deletShow = true;
        })
        .catch(() => {});
    },

    showimg(a) {
      if (!a) {
        return;
      }
      window.open(a);
    },

    startTimeLimit(val) {
      this.startTimeDisabled = val;
      this.ruleForm.validityStartTime = "";
      val == false
        ? (this.rules.validityStartTime[0].required = true)
        : (this.rules.validityStartTime[0].required = false);
    },

    endTimeLimit(val) {
      this.endTimeDisabled = val;
      this.ruleForm.validityEndTime = "";
      val == false
        ? (this.rules.validityEndTime[0].required = true)
        : (this.rules.validityEndTime[0].required = false);
    },

    addLink() {
      this.dialogTableVisible_o = true;
      this.getCourseList("");
    },

    getCourseList(title) {
      let data = {
        companyId: this.merchantId,
        status: 1,
        courseType: "",
        dataType: "",
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        title: title
      };
      queryCourse(data).then(res => {
        if (res.code === 200) {
          this.onlineClassList = res.data.list;
          this.totalItems = res.data.totalRecord;
        } else {
          this.$message.error(res.message);
        }
      })
    },

    closeAdd() {
      this.$confirm(
        "您确认要离开该页面吗- 您输入的数据可能不会被保存。",
        "确认关闭",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      )
        .then(() => {
          this.goBack();
        })
        .catch(() => {});
    },

    release() {
      if (!this.ruleForm.title) {
        this.$message({
          message: "请输入标题",
          type: "error"
        });
      } else if (!this.ruleForm.imgUrl) {
        this.$message({
          message: "请上传图片",
          type: "error"
        });
      } else if (
        !this.ruleForm.validityStartTime &&
        !this.ruleForm.onLineLimit
      ) {
        this.$message({
          message: "请选择开始时间, 或者选择即时上架",
          type: "error"
        });
      } else if (
        !this.ruleForm.validityEndTime &&
        !this.ruleForm.offlineLimit
      ) {
        this.$message({
          message: "请选择结束时间, 或者选择即时下架",
          type: "error"
        });
      } else {
        const confirmReleasText =
          "<dl>" +
          "<dt>确认发布当前编辑的广告内容？</dt>" +
          "<dd>广告发布后，系统将在‘有效期’展示广告内容</dd>" +
          "<dd>轮播广告位每次展示6条广告内容</dd>" +
          "<dd>系统检测到没有在有效期内广告时，该广告位显示默认广告图</dd>" +
          "<dd>同一时间广告数量超出最大显示范围，系统将按发布时间早晚依次展示</dd>" +
          "</dl>";
        this.$confirm(confirmReleasText, "确认发布", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          dangerouslyUseHTMLString: true
        })
          .then(() => {
            this.submitForm("ruleForm");
          })
          .catch(() => {});
      }
    },

    checkEndTime() {
      if(!this.ruleForm.validityEndTime) {
        return false;
      }
      if (!this.ruleForm.validityStartTime && !this.startTimeDisabled) {
        this.$message.error("开始日期不能为空");
      }

      

      if (this.ruleForm.validityEndTime <= this.ruleForm.validityStartTime) {
        this.$message.error("结束时间不能小于等于开始时间");
        this.ruleForm.validityEndTime = "";
      }
    },

    readioChange(row) {
      this.selectClass = row;
    },

    addOnlingCladdUrl() {
      this.ruleForm.linkUrl = this.selectClass.id;
      this.showUrl = this.selectClass.title;
      this.ruleForm.linkType = 1;
      this.dialogTableVisible_o = false;
    },
    addLinkUrl() {
      this.ruleForm.linkType = 0;
      this.showUrl = this.ruleForm.linkUrl;
      this.dialogTableVisible_o = false;
    },

    toPage() {
      this.getCourseList("");
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.radio = "";
      this.getCourseList("");
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.radio = "";
      this.getCourseList("");
    },

    searchClass() {
      this.getCourseList(this.searchClassInput);
    }
  }
};
</script>
<style scoped>
.uploadTip {
  font-size: 12px;
  color: #868181;
}
.el-date-editor.el-input {
  margin: 0 20px 20px 0;
}
.link-input {
  width: 70%;
}
.rowtwo .rowtwo-form {
  width: 450px;
}
.imgbox {
  display: inline-block;
  border: 1px dashed #dcdfe6;
}
.imgbox-v {
  width: 200px;
  height: 200px;
}
.imgbox img {
  display: block;
  width: auto;
  height: 200px;
}
.upload-btn {
  width: 100%;
  margin: 10px 0;
}
</style>
<style scope>
/* 确认发布的弹窗 */
.el-message-box__message dt {
  font-size: 16px;
}
.el-message-box__message dd {
  font-size: 12px;
}
.el-message-box__message dd::before {
  display: inline-block;
  vertical-align: middle;
  content: " ";
  background: #cac7c7;
  width: 6px;
  height: 6px;
  border-radius: 6px;
  margin-right: 10px;
}
/*.item .el*/
.add-link .item .el-input {
  width: 60px;
}
.add-link .line {
  width: 100%;
  height: 1px;
  background: #8c939d;
  margin: 20px 0;
}
.add-link .link-input {
  margin-left: 10px;
}
.delete-img {
  position: absolute;
  bottom: 11px;
  left: 105px;
}
.add-link .el-radio__label {
  display: none;
}
.add-link .el-tabs--border-card > .el-tabs__content {
  height: 425px;
}
.add-link .el-dialog__body {
  padding: 10px 0 0;
}
.add-link .btnBox {
  position: absolute;
  bottom: 10px;
  width: 100%;
  text-align: center;
}
.add-link .el-table .cell img {
  width: 50%;
}
.add-link .pageblock {
  display: flex;
  justify-content: center;
}
</style>


